<?php

class Database
{
	// Class variables -- Please specify here your MySQL server informations
	private $db_host = "localhost"; // Host : database server address
	private $db_port = ""; // Port : database port (optional)
	private $db_user = "root"; // User : database username
	private $db_pass = "ohnolol"; // Password : database user password
	private $db_base = "vnotes"; // Base : database name
	private $db_prfx = ""; // Prefix : tables custom prefix (optional)
	private $db_prst = ""; // Persistant : MySQL ONLY
	
	// DO NOT MODIFY BELOW
	
	// Errors
	private $errno = 0;
	private $error = "";
		
	// Connection informations
	private $link_id = ""; // DO NOT CHANGE THIS!
	
	// Query informations
	private $query_id = "";
	private $affected_rows = 0;
	
	// Constructor
	function __construct()
	{
		// Check connection informations
		if(		empty($this->db_host)
			or	empty($this->db_user)
			or	empty($this->db_pass))
		{
			$this->printerr('Invalid database configuration. Please edit /lib/Database.php');
		}
		
		// Connect
		$this->link_id = @mysql_connect($this->db_host,$this->db_user,$this->db_pass);
		
		// Connection failed
		if(!$this->link_id)
			$this->printerr('Error connecting to MySQL server');
		
		// Select database
		if(!@mysql_select_db($this->db_base,$this->link_id))
			$this->printerr('Error selecting database <b>'+ $this->db_base + '</b>');
			
		// Security : now that we have the link, we don't need the informations anymore
		$this->db_host = '';
		$this->db_user = '';
		$this->db_pass = '';
		$this->db_base = '';
	}
	
	##########################
	# Executes SQL query
	# Param : string
	# Returns : query
	public function query($sql)
	{				
		// Do query
		$this->query_id = @mysql_query($sql);
		
		// Query error
		if(!$this->query_id)
			$this->printerr('Error running query &lt;&lt;'.$sql.'&gt;&gt; '.mysql_error());
		
		// Affected rows
		$this->affected_rows = @mysql_affected_rows($this->link_id);
		
		return $this->query_id;
	}
	
	##########################
	# Closes connection to database
	# Param :
	# Returns :
	public function close()
	{
		if(!@mysql_close($this->link_id))
			$this->printerr('Error in closing database');
	}
	
	##########################
	# Secures query against injections
	# Param : string
	# Returns : string
	public function secure($str)
	{
		if(get_magic_quotes_runtime())
			$str = stripslashes($str);
		return @mysql_real_escape_string($str, $this->link_id);
	}
	
	##########################
	# Fetches results, one line at a time, with association (mysql_fetch_assoc)
	# Param : query (if not specified, last used)
	# Returns : array
	public function fetch($query_id = -1)
	{
		if($query_id != -1)
			$this->query_id = $query_id;
			
		if(isset($this->query_id))
			$result = @mysql_fetch_assoc($this->query_id);
		else
			$this->printerr('Invalid query id. Records could not be fetched.');
			
		return $result;
	}
	
	##########################
	# Fetches all results at once
	# Param : query (if not specified, last used)
	# Returns : array
	# Note : same as fetch(), but returns the entire array of results
	public function fetch_all($query_id = -1)
	{
		if($query_id != -1)
			$this->query_id = $query_id;
			
		$results = array();
		
		while($row = $this->fetch($query_id))
			$results[] = $row;
			
		$this->free($query_id);
		return $results;
	}
	
	##########################
	# Fetches first result
	# Param : string
	# Returns : array
	public function fetch_first($sql)
	{
		$query_id = $this->query($sql);
		$result = $this->fetch($query_id);
		$this->free($query_id);
		return $result;
	}
	
	##########################
	# Show number of matched rows
	# Param : 
	# Returns : int
	public function num_rows()
	{
		$r = @mysql_num_rows($this->query_id);
		if(!is_numeric($r) or $r < 1)
			$r = 0;
		return $r;
	}
	
	##########################
	# Select lines
	# Param : SELECT b FROM a WHERE c LIMIT d ORDER BY e
	# Returns : query (for use with fetch functions)
	public function select($a, $b = '*', $c = 1, $d = 'none', $e = 'id DESC')
	{	
		// conditions : where a=... and b=... and c=...
		if(is_array($c))
		{
			$arg = '';
			foreach($c as $k=>$v)
				$arg .= $this->secure($k)." = '".$this->secure($v)."' AND ";
			$c = rtrim($arg, "AND ");
		}
		
		// limit results ?
		if($d == 'none')
			$limit = '';
		else
			$limit = " LIMIT ".$this->secure($d);
		
		// write query
		$sql =  "SELECT ".$this->secure($b)." FROM ".$this->db_prfx.$this->secure($a)." ".
				"WHERE $c ".
				"ORDER BY ".$this->secure($e).
				$limit.";";
								
		// send query
		return $this->query($sql);
	}
	
	##########################
	# Return $field of the FIRST line of the given $table
	# Param : field, table
	# Returns : field value
	public function getFirst($field,$table)
	{		
		$this->select($table,$field,1,1,"id ASC");
		$data = $this->fetch();
		return $data[$field];
	}
	
	##########################
	# Return $field of the LAST line of the given $table
	# Param : field, table
	# Returns : field value
	public function getLast($field,$table)
	{		
		$this->select($table,$field,1,1);
		$data = $this->fetch();
		return $data[$field];
	}
	
	
	##########################
	# Updates table
	# Param : table to update, assoc array with data, WHERE condition
	# Returns : query (for use with fetch functions)
	public function update($table, $data, $where = '1')
	{
		$sql = "UPDATE ".$this->db_prfx.$table." SET ";
		
		foreach($data as $k=>$v)
		{
			if(strtolower($v) == 'null')
				$sql .= "$k = NULL, ";
			elseif(strtolower($v) == 'now()')
				$sql .= "$k = NOW(), ";
			else
				$sql .= "$k = '".$this->secure($v)."', ";
		}
		
		$sql = rtrim($sql, ", ") . ' WHERE '.$where.';';
		return $this->query($sql);
	}
	
	##########################
	# Insert into table
	# Param : table, assoc array with data
	# Returns : id of inserted record or false
	public function insert($table, $data)
	{
		$sql = "INSERT INTO ".$this->db_prfx.$table." ";
		$a = '';
		$b = '';
		
		if(!isset($data) or empty($data) or !is_array($data))
			$this->printerr("You must pass an array as argument to insert() function");
		
		foreach($data as $k=>$v)
		{
			$a .= "$k, ";
			if(strtolower($v) == 'null')
				$b .= "NULL, ";
			elseif(strtolower($v) == "now()")
				$b .= "NOW(), ";
			else
				$b .= "'".$this->secure($v)."', ";
		}
		
		$sql .= "(".rtrim($a, ', ').") VALUES (".rtrim($b, ', ').");";
		
		if($this->query($sql))
			return mysql_insert_id($this->link_id);
		else
			return false;
	}
	
	##########################
	# Frees results
	# Param : query (if not specified, last used)
	# Returns : 
	public function free($query_id = -1)
	{
		if($query_id != -1)
			$this->query_id = $query_id;
		
		if($this->query_id != 0 and !@mysql_free_result($this->query_id))
			$this->printerr('Error freeing query');
	}
	
	##########################
	# Shows error
	# Param : string
	# Returns : 
	# http://www.ricocheting.com/scripts/setup/mysql/Database.class.phps [Licence : GNU GPL]
	private function printerr($err = '')
	{
		if($this->link_id > 0)
		{
			$this->error = mysql_error($this->link_id);
			$this->errno = mysql_errno($this->link_id);
		}
		else
		{
			$this->error = mysql_error();
			$this->errno = mysql_errno();
		}
		?>
			<table align="center" border="1" cellspacing="0" style="background:lightgrey;color:black;width:80%;">
			<tr><th colspan=2>Database Error</th></tr>
			<tr><td align="right" valign="top">Message:</td><td><?php echo $err; ?></td></tr>
			<?php if(strlen($this->error)>0) echo '<tr><td align="right" valign="top" nowrap>MySQL Error:</td><td>'.$this->error.'</td></tr>'; ?>
			<tr><td align="right">Date:</td><td><?php echo date("l, F j, Y \a\\t g:i:s A"); ?></td></tr>
			<tr><td align="right">Script:</td><td><a href="<?php echo @$_SERVER['REQUEST_URI']; ?>"><?php echo @$_SERVER['REQUEST_URI']; ?></a></td></tr>
			<?php if(strlen(@$_SERVER['HTTP_REFERER'])>0) echo '<tr><td align="right">Referer:</td><td><a href="'.@$_SERVER['HTTP_REFERER'].'">'.@$_SERVER['HTTP_REFERER'].'</a></td></tr>'; ?>
			</table>
		<?php
		exit();
	}
	
	##########################
	# Converts a String from ISO-LATIN-1 to UTF8
	# Param : string
	# Returns : string
	public static function latin1_to_utf8($string)
	{
		return iconv("ISO-8859-1","UTF-8",$string);
	}
	
	##########################
	# Converts a String from UTF8 to ISO-LATIN-1
	# Param : string
	# Returns : string
	public static function utf8_to_latin1($string)
	{
		return iconv("UTF-8","ISO-8859-1",$string);
	}
	
	/*
	* Nom : getFDate()
	* But : retourne une partie d'une valeur date créée par PHP avec la fonction date()
	* Info : Guillaume Florimond, 15/03/2008
	* Param 1 : $valeur : la date PHP à traiter
	* Param 2 : $operateur : la partie à extraire
	* Param 2 : $operateur peut être 's' (seconde), 'i' (minutes), 'H' (heures), 'd' (jours), 'm' (mois) ou 'Y' (années)
	*/
	public static function getFDate($valeur,$operateur)
	{
		switch($operateur)
		{
			// Secondes
			case 's': $res = substr($valeur, 17, 2); break;
			// Minutes
			case 'i': $res = substr($valeur, 14, 2); break;
			// Heures
			case 'H': $res = substr($valeur, 11, 2); break;
			// Jours
			case 'd': $res = substr($valeur, 8, 2); break;
			// Mois
			case 'm': $res = substr($valeur, 5, 2); break;
			// Années
			case 'Y': $res = substr($valeur, 0, 4); break;
			// Par défaut
			default: $res = NULL; break;
		}
		return $res;
	}
	
	public static function getFrenchDate($date)
	{
		$d = Database::getFDate($date,'d');
		$m = substr(Database::name_month(Database::getFDate($date,'m')),0,4);
		$Y = Database::getFDate($date,'Y');
		$H = Database::getFDate($date,'H');
		$i = Database::getFDate($date,'i');
		$s = Database::getFDate($date,'s');
		$nd = "$d $m, $H:$i";
		return $nd;
	}
	
	// Donne un nom au mois passé en argument
	public static function name_month($mois) 
	{
		$M = Array("", "Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Aôut", "Septembre", "Octobre", "Novembre", "Décembre");
		return (intval($mois) > 0 && intval($mois) < 13) ? $M[intval($mois)] : "Indéfini";
	}
}
?>